<?php
/**
 * @since   2022-02-15
 * @author  zhaoxiang <zhaoxiang051405@gmail.com>
 */

namespace App\Controller\Admin;

use App\Constants\ErrorCode;
use App\Context\UserInfoContext;
use App\Controller\AbstractController;
use App\Service\ToolService;
use Hyperf\Context\Context;
use Hyperf\Database\Schema\Schema;
use function Hyperf\Support\env;

class BaseController extends AbstractController {
    private array    $debug     = [];

    public function uInfo(): array {
        $userData = Context::get(UserInfoContext::class)->userInfo;
        if ($userData) {
            $userDataArr = $userData;
        } else {
            $userDataArr = [];
        }

        return $userDataArr;
    }

    /**
     * 成功的返回
     * @param array $data
     * @param string $msg
     * @param int $code
     * @return array
     * @author zhaoxiang <zhaoxiang051405@gmail.com>
     */
    public function buildSuccess(array $data = [], string $msg = '操作成功', int $code = ErrorCode::SUCCESS): array {
        $return = [
            'code' => $code,
            'msg'  => $msg,
            'data' => $data
        ];
        if (env('APP_ENV', 'prod') === 'dev' && !empty($this->debug)) {
            $return['debug'] = $this->debug;
        }

        return $return;
    }

    /**
     * 错误的返回
     * @param int $code
     * @param string $msg
     * @param array $data
     * @return array
     * @author zhaoxiang <zhaoxiang051405@gmail.com>
     */
    public function buildFailed(int $code, string $msg = '操作失败', array $data = []): array {
        $return = [
            'code' => $code,
            'msg'  => $msg,
            'data' => $data
        ];
        if (env('APP_ENV', 'prod') === 'dev' && !empty($this->debug)) {
            $return['debug'] = $this->debug;
        }

        return $return;
    }

    /**
     * debug参数收集
     * @param $data
     * @author zhaoxiang <zhaoxiang051405@gmail.com>
     */
    protected function debug($data): void {
        if ($data) {
            $this->debug[] = $data;
        }
    }

    /**
     * 获取客户端IP
     * @return array|string|null
     */
    public function getIp(): array|string|null {
        return (new ToolService())->getClientIp();
    }

    /**
     * 数据过滤
     * @param $table
     * @param $data
     * @param int $type
     * @return array
     */
    public function filterData($table, $data, int $type = 2): array {
        $tableColumn = Schema::getColumnListing($table);
        if ($type === 1) {
            unset($data['id']);
        }

        return array_filter($data, static function ($key) use ($tableColumn) {
            return in_array($key, $tableColumn, true);
        }, ARRAY_FILTER_USE_KEY);
    }
}
